package com.zzy.demo.config;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.zzy.demo.service.mqtt.EventCallback;

@Configuration
public class MqttConfig {
	
	@Value("${mqtt.host}")
	private String host;
	
	@Value("${mqtt.username}")
	private String username;
	
	@Value("${mqtt.password}")
	private String password;
	
	@Value("${mqtt.clientId}")
	private String clientId;
	
	@Value("${mqtt.topic}")
	private String topic;
	
	
	@Bean
	public MqttClient mqttClient() throws MqttException {
		MqttClient mqttClient = new MqttClient(host, clientId, new MemoryPersistence());
		
		MqttConnectOptions options = new MqttConnectOptions();
		options.setUserName(username);
		options.setPassword(password.toCharArray());
		options.setConnectionTimeout(10);/// 默认：30
		options.setAutomaticReconnect(true);// 默认：false
		options.setCleanSession(false);// 默认：true
		// options.setKeepAliveInterval(20);//默认：60
		
		mqttClient.setCallback(new EventCallback());
		mqttClient.connect(options);
		return mqttClient;
	}

	

}
